﻿using System;
using UnityEngine;

public class SingleBaseMono<T> : MonoBehaviour,ISingleBaseMono where T : SingleBaseMono<T>
{
    private static T _instance;
    public static T Instance
    {
        get
        {
            //如果版本比较高这里可以选择使用复合分配
            //return _instance ??= new Lazy<GameObject>(() => { return new GameObject(typeof(T).Name+"_Single"); }, true).Value.AddComponent<T>();
            //return _instance ?? new Lazy<GameObject>(() => { return new GameObject(typeof(T).Name + "_Single"); }, true).Value.AddComponent<T>();
            if(_instance == null)
            {
                _instance = new Lazy<GameObject>(() => { return new GameObject(typeof(T).Name + "_Single"); }, true).Value.AddComponent<T>();
                //初始化
                _instance.OnInit();
            }
            return _instance;
        }
        private set
        {
            _instance = value;
        }
    }

    public void Awake()
    {
        DontDestroyOnLoad(this);
    }

    /// <summary>
    /// 初始化组件、数据
    /// </summary>
    public virtual void OnInit() { }

    /// <summary>
    /// 清空组件、数据（请将base.Claer()放在清空所有数据后调用）
    /// </summary>
    public virtual void OnClear()
    {
        DestroyImmediate(gameObject);
        _instance = null;
    }
}
